package com.utils.wifi

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.os.Build

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2021/6/17
 */
class WifiConnectReceiver : BroadcastReceiver() {
    private val TAG = "WifiUtils"
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) {
            return
        }
        if (intent.action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
            val wifiState =
                    intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
            when (wifiState) {
                WifiManager.WIFI_STATE_DISABLED -> {
                    WifiUtils.wifiStateCallBack?.get()?.onWifiDisable()
                }
                WifiManager.WIFI_STATE_DISABLING -> {
                    WifiUtils.wifiStateCallBack?.get()?.onWifiDisabling()
                }
                WifiManager.WIFI_STATE_ENABLED -> {
                    WifiUtils.wifiStateCallBack?.get()?.onWifiEnable()
                }
                WifiManager.WIFI_STATE_ENABLING -> {
                    WifiUtils.wifiStateCallBack?.get()?.onWifiEnabling()
                }
                WifiManager.WIFI_STATE_UNKNOWN -> {
                    WifiUtils.wifiStateCallBack?.get()?.onWifiUnknown()
                }
            }
        } else if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                //安卓10以上是否连接成功不需要此回调
                return
            }
            val info =
                    intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)
            val state = info?.state
            if (state == NetworkInfo.State.CONNECTED) {
                //连接成功
                WifiUtils.wifiStateCallBack?.get()?.onConnected()
            }
        }
    }
}